<template>
  <el-form :model="form" ref="formRef">
    <el-row>
      <template v-for="(item, key) in cformOpt?.items" :key="key">
        <!-- ts类型缩小 -->
        <FormItem v-on="{ ...itemEmit }" :ref="formItemRef" :itemValue="form[key]" :item="item" :itemKey="key">
          <template #otherItem="{ item, key }"><slot name="otherItem" :form="form" :item="item" :key="key"></slot> </template>
        </FormItem>
      </template>
      <slot name="otherFormItem" :form="form"></slot>
      <el-form-item>
        <slot name="otherBtn" :form="form"></slot>
      </el-form-item>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import FormItem from "./formItem.vue";
import { formProps, formEmit, fileType, formData } from "@/components/Cform/form";
import { useDrag } from "@/store/modules/drag";
import { deepClone } from "@/assets/utils/deepClone";
import { combineObj } from "@/assets/utils";
const dragStore = useDrag();
const route = useRoute();
const emit = defineEmits([...formEmit]);
const props = defineProps([...formProps]);
const form = ref(deepClone(props.formParams) || {});
const formRef = ref();
const formItemRefs = ref<CeditorType[]>([]);
const formItemRef = (el: CeditorType) => {
  let hasItem = formItemRefs.value.find((item) => item === el);
  if (hasItem) return;
  if (el) {
    formItemRefs.value.push(el);
  }
};
const submitData = ref<any>(null);
let codePageCformOpt = (cformOpteCopy) => {
  if (route.name !== "coderCreate") return;
  let currentItem = {};
  let currentRender = dragStore.renderData.find((item) => {
    return item.id == props.id;
  });
  currentRender.childrens.map((item) => {
    currentItem[item.props.itemValue] = item.props.item;
  });
  cformOpteCopy.items = currentItem;
};
const submitForm = async () => {
  let valided;
  await formRef.value.validate(async (valid: boolean) => {
    valided = valid;
  });
  if (!valided) return;
  // try {
  let cformOpteCopy = deepClone(props.cformOpt);
  codePageCformOpt(cformOpteCopy);
  submitData.value = { ...form.value };
  Object.keys(submitData.value).forEach((key) => {
    let item = cformOpteCopy.items[key];
    if (!item?.hide && fileType.includes(item?.type as CuploadFileTypesType) && !submitData.value[key] && item.hasrules) {
      throw `请上传${item.type == "uVideo" ? "视频" : "图片"}`;
    }
    if (submitData.value[key]?.constructor == Array && !item?.notHandleArray) {
      submitData.value[key] = submitData.value[key].length > 0 && cformOpteCopy.handleToString ? submitData.value[key].join(",") : JSON.stringify(submitData.value[key]);
    }
  });
  if (cformOpteCopy.beforeSubmit) {
    let msge;
    emit("beforeSubmit", {
      submitData,
      fn: (msg: string) => {
        msge = msg;
      }
    });
    if (msge) return ElMessage.error(msge);
  }
  let res;
  if (cformOpteCopy.saveMethod == "put" || submitData.value.id) {
    let surl = submitData.value.id && props.cformOpt.updateUrl ? cformOpteCopy.updateUrl : cformOpteCopy.saveUrl;
    res = await hfoRequest.put({ url: surl, data: submitData.value });
  } else {
    let surl = cformOpteCopy.saveUrl;
    res = await hfoRequest.post({ url: surl, data: submitData.value });
  }
  if (res?.flag) {
    return res;
  }
  // } catch (error) {
  //   ElMessage.error(error as MessageParamsWithType);
  // }
};
async function formValid() {
  let valided;
  await formRef.value.validate(async (valid: boolean) => {
    valided = valid;
  });
  if (!valided) return true;
}
const resetfile = (e: any) => {
  form.value = {};
  combineObj(form.value, props.formParams, true);
  combineObj(form.value, e, true);
  for (let item in formItemRefs.value) {
    let key = formItemRefs.value[item].itemKey;
    formItemRefs.value[item].initFormRef(form.value[key]);
  }
};
const changeRadio = ({ e, key, item }: changeRadioType) => {
  form.value[key] = e;
  console.log(e);
  emit("changeRadio", { e, key, item, form: form.value });
};
function updateValue(itemKey, data) {
  form.value[itemKey] = data;
}
let formDate = new formData(props as CformPropsType, emit);
const itemEmit = {
  otherGetFileFn: formDate.formEmitsObj.otherGetFileFn,
  beforeUpload: formDate.formEmitsObj.beforeUpload,
  changeProps: formDate.formEmitsObj.changeProps,
  updateValue: updateValue,
  changeRadio: changeRadio
};
defineExpose({
  form,
  submitForm,
  resetfile,
  formRef,
  formValid,
  formItemRef
});
</script>

<style lang="scss">
.formItemTip {
  position: absolute;
  color: #f00;
  font-size: 12px;
  bottom: -25px;
  left: 0;
  width: max-content;
  z-index: 111;
}

.el-form--inline {
  max-width: 1300px;
}

.el-form {
  .el-form-item {
    position: relative;
  }
}

.el-popper {
  z-index: 2600 !important;
}
</style>
